/**
 * 认证状态管理Hook
 * 专门处理token持久化、认证状态监听和自动刷新
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { message } from "antd";
import { AuthService } from "../utils/auth";
import { authAPI } from "../services/apiService";
import { User } from "../contexts/UserContext";
import { UserInfo } from "../types/api";

interface AuthState {
  isAuthenticated: boolean;
  user: User | null;
  loading: boolean;
  error: string | null;
}

// 默认权限配置
const DEFAULT_PERMISSIONS = {
  admin: [
    "user.manage",
    "student.manage",
    "teacher.manage",
    "course.manage",
    "discussion.manage",
    "system.config",
    "data.export",
    "audit.view",
  ],
  teacher: [
    "course.create",
    "course.edit",
    "course.view",
    "student.view",
    "grade.manage",
    "discussion.moderate",
    "resource.upload",
    "exam.create",
    "analysis.view",
  ],
  student: [
    "course.view",
    "discussion.create",
    "discussion.reply",
    "discussion.like",
    "resource.download",
    "exam.take",
    "grade.view",
  ],
};

// 将UserInfo转换为User
function convertUserInfoToUser(userInfo: UserInfo): User {
  return {
    id: userInfo.id,
    name: userInfo.name,
    role: userInfo.type, // type -> role
    email: userInfo.email || "",
    phone: userInfo.phone,
    avatar: userInfo.avatar,
    permissions: DEFAULT_PERMISSIONS[userInfo.type] || [],
    // 教师专有字段
    department: userInfo.department,
    title: userInfo.title,
    subject: userInfo.subject,
    // 学生专有字段
    studentId: userInfo.studentId,
    major: userInfo.major,
    className: userInfo.className,
    grade: userInfo.grade,
  };
}

export function useAuth() {
  const [authState, setAuthState] = useState<AuthState>({
    isAuthenticated: false,
    user: null,
    loading: true,
    error: null,
  });

  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // 初始化认证状态
  const initializeAuth = useCallback(async () => {
    try {
      console.log("🔐 初始化认证状态...");

      // 初始化AuthService（处理cookie迁移等）
      AuthService.initialize();

      // 检查本地存储的认证状态
      if (AuthService.isAuthenticated()) {
        const storedUser = AuthService.getUser();
        const token = AuthService.getToken();

        console.log("✅ 发现本地认证信息:", {
          hasToken: !!token,
          hasUser: !!storedUser,
          remember: AuthService.getRememberMe(),
        });

        if (storedUser && token) {
          // 直接使用本地存储的用户信息，不进行额外验证
          console.log("✅ 使用本地存储的认证状态");

          setAuthState({
            isAuthenticated: true,
            user: storedUser,
            loading: false,
            error: null,
          });

          // 启动自动刷新
          startTokenRefresh();
        } else if (token) {
          // 有token但没有用户信息，尝试获取（但不阻塞认证状态）
          console.log("ℹ️ 有Token但缺少用户信息，尝试获取...");

          // 先设置为已认证状态，避免页面跳转
          setAuthState({
            isAuthenticated: true,
            user: null, // 临时为null，后续获取
            loading: false,
            error: null,
          });

          try {
            const userInfo = await authAPI.getUserInfo();
            const user = convertUserInfoToUser(userInfo);

            AuthService.setToken(token, user, {
              remember: AuthService.getRememberMe(),
            });

            setAuthState({
              isAuthenticated: true,
              user: user,
              loading: false,
              error: null,
            });

            console.log("✅ 获取用户信息成功");
            startTokenRefresh();
          } catch (error) {
            console.warn("⚠️ 获取用户信息失败，但保持登录状态");
            // 即使获取用户信息失败，也不退出登录，因为token可能仍然有效
          }
        } else {
          // 没有有效token
          setAuthState({
            isAuthenticated: false,
            user: null,
            loading: false,
            error: null,
          });
        }
      } else {
        // 没有有效的认证信息
        console.log("ℹ️ 未发现有效认证信息");
        setAuthState({
          isAuthenticated: false,
          user: null,
          loading: false,
          error: null,
        });
      }
    } catch (error) {
      console.error("❌ 认证初始化失败:", error);
      // 即使初始化失败，也尝试保持现有状态
      const token = AuthService.getToken();
      const user = AuthService.getUser();

      if (token && user) {
        console.log("🔄 初始化失败但保持现有认证状态");
        setAuthState({
          isAuthenticated: true,
          user: user,
          loading: false,
          error: null,
        });
      } else {
        setAuthState({
          isAuthenticated: false,
          user: null,
          loading: false,
          error: "认证初始化失败",
        });
      }
    }
  }, []);

  // 启动Token自动刷新
  const startTokenRefresh = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }

    // 每25分钟刷新一次token（假设token过期时间为30分钟）
    intervalRef.current = setInterval(
      async () => {
        try {
          const newToken = await AuthService.refreshToken();
          if (newToken) {
            console.log("🔄 Token自动刷新成功");
          } else {
            console.warn("⚠️ Token自动刷新失败，用户需要重新登录");
            logout();
          }
        } catch (error) {
          console.error("❌ Token自动刷新失败:", error);
          logout();
        }
      },
      25 * 60 * 1000
    ); // 25分钟
  }, []);

  // 停止Token自动刷新
  const stopTokenRefresh = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }, []);

  // 登录
  const login = useCallback(
    async (
      phone: string,
      password: string,
      type: "admin" | "teacher" | "student",
      rememberMe: boolean = true
    ) => {
      try {
        setAuthState((prev) => ({ ...prev, loading: true, error: null }));

        console.log("🔐 开始登录流程...");

        const response = await authAPI.login({
          phone,
          password,
          type,
        });

        if (response && response.token && response.userInfo) {
          // 转换用户信息
          const user = convertUserInfoToUser(response.userInfo);

          // 保存认证信息
          AuthService.setToken(response.token, user, {
            remember: rememberMe,
            expiresIn: response.expiresIn,
          });

          setAuthState({
            isAuthenticated: true,
            user: user,
            loading: false,
            error: null,
          });

          console.log("✅ 登录成功:", {
            user: user.name,
            remember: rememberMe,
            token: response.token.substring(0, 20) + "...",
          });

          // 启动自动刷新
          startTokenRefresh();

          message.success("登录成功");
          return response;
        } else {
          throw new Error("登录响应格式错误");
        }
      } catch (error: any) {
        console.error("❌ 登录失败:", error);

        const errorMessage = error.message || "登录失败";
        setAuthState((prev) => ({
          ...prev,
          loading: false,
          error: errorMessage,
        }));

        message.error(errorMessage);
        throw error;
      }
    },
    [startTokenRefresh]
  );

  // 登出
  const logout = useCallback(() => {
    console.log("🚪 执行登出操作...");

    // 停止自动刷新
    stopTokenRefresh();

    // 清除认证信息
    AuthService.removeToken();

    // 更新状态
    setAuthState({
      isAuthenticated: false,
      user: null,
      loading: false,
      error: null,
    });

    console.log("✅ 登出完成");
    message.info("已退出登录");
  }, [stopTokenRefresh]);

  // 手动刷新认证状态
  const refreshAuth = useCallback(async () => {
    console.log("🔄 手动刷新认证状态...");
    await initializeAuth();
  }, [initializeAuth]);

  // 检查权限
  const hasPermission = useCallback(
    (permission: string): boolean => {
      if (!authState.user) return false;
      
      // 超级管理员拥有所有权限
      if (authState.user.role === "admin") {
        return true;
      }
      
      return authState.user.permissions?.includes(permission) || false;
    },
    [authState.user]
  );

  // 组件挂载时初始化
  useEffect(() => {
    initializeAuth();

    // 监听存储变化（用于多标签页同步）
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "authToken" || e.key === "authUser") {
        console.log("📱 检测到其他标签页认证状态变化，同步状态...");
        refreshAuth();
      }
    };

    window.addEventListener("storage", handleStorageChange);

    // 组件卸载时清理
    return () => {
      stopTokenRefresh();
      window.removeEventListener("storage", handleStorageChange);
    };
  }, [initializeAuth, refreshAuth, stopTokenRefresh]);

  return {
    // 状态
    isAuthenticated: authState.isAuthenticated,
    user: authState.user,
    loading: authState.loading,
    error: authState.error,

    // 操作
    login,
    logout,
    refreshAuth,
    hasPermission,

    // 工具方法
    getToken: AuthService.getToken,
    getRememberMe: AuthService.getRememberMe,
  };
}

export default useAuth;
